from django.shortcuts import render
from django.views.generic.base import View
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
from django.db.models import Q

from courses.models import Course, CourseResourse, Video
from operation.models import UserFavorite, UserComments, UserCourse
from utils.mixin_utils import LoginRequireMixin
# Create your views here.


class CourseListView(View):
    def get(self, request):
        all_courses = Course.objects.all().order_by('-add_time')
        hot_courses = Course.objects.all().order_by('-click_nums')[:3]

        # 实现全局搜索功能
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            all_courses = all_courses.filter(Q(name__icontains=search_keywords) | Q(desc__icontains=search_keywords)
                                             | Q(detail__icontains=search_keywords)).order_by()  # 在数据库中对keywords进行搜索

        # 对课程进行排序
        sort = request.GET.get('sort', '')
        if sort == 'students':
            all_courses = all_courses.order_by('-students')
        elif sort == 'hot':
            all_courses = all_courses.order_by('-click_nums')

        # 对课程进行分类
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_courses, 9, request=request)
        courses = p.page(page)
        return render(request, 'course-list.html', {'all_courses': courses, 'sort': sort, 'hot_courses': hot_courses})


class CourseDetailView(View):
    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))

        course.click_nums += 1
        course.save()

        has_fav_course = False
        has_fav_org = False

        if request.user.is_authenticated():
            if UserFavorite.objects.filter(user=request.user, fav_id=course.id, fav_type=1):    # 判断是否收藏了课程
                has_fav_course = True
            if UserFavorite.objects.filter(user=request.user, fav_id=course.course_org.id, fav_type=2):    # 判断是否收藏了课程机构
                has_fav_org = True

        tag = course.tag
        if tag:
            relate_courses = Course.objects.filter(tag=tag)[:3]
        else:
            relate_courses = []

        return render(request, 'course-detail.html', {
            'course': course,
            'relate_courses': relate_courses,
            'has_fav_course': has_fav_course,
            'has_fav_org': has_fav_org,
        })


class CourseInfoView(LoginRequireMixin, View):
    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))
        course.students += 1
        course.save()
        # 查询该用户点击开始学习后是否保存了课程，如果没有，就保存课程
        usercourse = UserCourse.objects.filter(user=request.user, course=course)
        if not usercourse:
            course_user = UserCourse(user=request.user, course=course)
            course_user.save()

        # 取出学过该课的同学还学过的课程
        user_courses = UserCourse.objects.filter(course=course)   # 取出当前课程下的所有用户
        user_ids = [user_course.user.id for user_course in user_courses]   # 拿到当前课程下所有用户的id
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)  # 拿到所有用户的所有课程
        course_ids = [user_course.course.id for user_course in all_user_courses]  # 拿到所有课程的id
        relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums').exclude(id=course.id)[0:3]

        all_resources = CourseResourse.objects.filter(course=course)
        return render(request, 'course-video.html', {'course': course,
                                                     'all_resources': all_resources,
                                                     'relate_courses': relate_courses,
         })


class CommentsView(LoginRequireMixin, View):
    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))

        # 取出学过该课的同学还学过的课程
        user_courses = UserCourse.objects.filter(course=course)  # 取出当前课程下的所有用户
        user_ids = [user_course.user.id for user_course in user_courses]  # 拿到当前课程下所有用户的id
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)  # 拿到所有用户的所有课程
        course_ids = [user_course.course.id for user_course in all_user_courses]  # 拿到所有课程的id
        relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums').exclude(id=course.id)[0:3]

        all_resources = CourseResourse.objects.filter(course=course)
        all_comments = UserComments.objects.all().order_by('-comments_praise')
        # 对课程留言进行分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_comments, 5, request=request)
        comments = p.page(page)
        return render(request, 'course-comment.html', {'course': course,
                                                       'all_comments': comments,
                                                       'all_resources': all_resources,
                                                       'relate_courses': relate_courses
                                                       })


class AddCommentsView(View):
    # 用户添加评论课程
    def post(self, request):
        if not request.user.is_authenticated():
            return HttpResponse('{"status":"fail", "msg":"用户未登录"}', content_type='application/json')

        course_id = request.POST.get('course_id', 0)
        comments = request.POST.get('comments', '')
        if int(course_id) > 0 and comments:
            user_comment = UserComments()
            course = Course.objects.get(id=int(course_id))
            user_comment.course = course
            user_comment.comments = comments
            user_comment.user = request.user
            user_comment.save()
            return HttpResponse('{"status":"success", "msg":"添加成功"}', content_type='application/json')
        else:
            return HttpResponse('{"status":"fail", "msg":"添加失败"}', content_type='application/json')


class VideoPlayView(LoginRequireMixin, View):
    # 视频播放页面
    def get(self, request, video_id):
        video = Video.objects.get(id=int(video_id))
        course = video.lesson.course
        course.students += 1
        course.save()

        # 查询该用户点击开始学习后是否保存了课程，如果没有，就保存课程
        usercourse = UserCourse.objects.filter(user=request.user, course=course)
        if not usercourse:
            course_user = UserCourse(user=request.user, course=course)
            course_user.save()

        # 取出学过该课的同学还学过的课程
        user_courses = UserCourse.objects.filter(course=course)   # 取出当前课程下的所有用户
        user_ids = [user_course.user.id for user_course in user_courses]   # 拿到当前课程下所有用户的id
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)  # 拿到所有用户的所有课程
        course_ids = [user_course.course.id for user_course in all_user_courses]  # 拿到所有课程的id
        relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums').exclude(id=course.id)[0:3]

        all_resources = CourseResourse.objects.filter(course=course)
        return render(request, 'course-play.html', {'course': course,
                                                     'all_resources': all_resources,
                                                     'relate_courses': relate_courses,
                                                     'video': video,
         })

